package com.lee.utils;

import java.math.BigDecimal;
import java.text.DecimalFormat;

/**
 * @author lee
 */
public class ByteChange {

    /**
     * 传入一个字符串类型的数字大小，实现文件大小的转化，如 B - KB - MB - GB
     * @param o
     * @return
     */
    public static String getSize(String o){
        BigDecimal bigDecimal = new BigDecimal(o);
        long i = bigDecimal.longValue();
        String result = "";
        long kb = 1024;
        long mb = kb * 1024;
        long gb = mb * 1024;

        /*实现保留小数点两位*/
        DecimalFormat df = new DecimalFormat("#.00");

        if (i >= gb){
            result =  df.format((float) i / gb) + "GB";
        }else if(i >= mb){
            result =  df.format((float) i / mb) + "MB";
        }else if(i >= kb){
            result = String.format("%.2f", (float) i / kb) + "KB";
        }else {
            result =  i + "B";
        }
        return result;
    }

    public static void main(String[] args) {
        String size = getSize("4536000000");
        System.out.println("数据大小为 " + size);
    }
}
